import 'package:get/get.dart';
import 'package:sports_new/entity/other/play_entity.dart';
import 'package:sports_new/server/api/king_api.dart';
import 'package:sports_new/utils/utils.dart';
import '../../entity/king/king_entity.dart';
import '../../utils/user.dart';

class KingDetailLogic extends GetxController{
  KingEntity? data;
  List<String> betWin = ["主胜","平局","客胜"];
  List<String> betPoints = List.generate(8, (index) => "$index球${index == 7?"及以上":""}");
  List<String> result = [];
  List<String> pointsResult = [];
  List<int> winIndex = [];
  List<int> pointsIndex = [];
  String handicap = "0";
  bool hasCommit = false;

  @override
  void onReady() async{
    User.needLogin(() async=> await getData(),fail: Get.back);
    super.onReady();
  }

  void setWinIndex(int value,bool choose) {
    choose?winIndex.removeWhere((element) => element==value)
      :winIndex.add(value);
    update();
  }
  void setPointsIndex(int value,bool choose) {
    choose?pointsIndex.removeWhere((element) => element==value)
      :pointsIndex.add(value);
    update();
  }

  Future getData() async{
    data = await KingApi.getKingDetail(Get.arguments);
    handicap = "${data?.spfLine.hasValue == true && data!.spfLine! > 0?"+":""}"
      "${data?.spfLine ?? ""}";
    if(data?.item.hasValue == true){
      decodePlayType(data!.item!).forEach((element) {
        if(element.playType == playType["胜平负"]
          || element.playType == playType["让球胜平负"]) {
          winIndex = betWin.indexOn(element.choices ?? []);
        }else{
          pointsIndex = betPoints.indexOn(element.choices ?? []);
        }
      });
    }
    result = [
      if(data?.spf != null)
        codeToResult[data!.spf]!,
      if(data?.zjq != null)
        "${data?.zjq}球${data?.zjq == 7?"及以上":""}"
    ];
    update();
  }

  Future commit() async{
    List<PlayEntity> list = [];
    if(winIndex.isNotEmpty) {
      list.add(PlayEntity(
        matchId: data?.matchId,
        playType: handicap != "0"?"让球胜平负":"胜平负",
        handicap: handicap.toInt().toString(),
        items: List.generate(winIndex.length, (index) =>
          betWin[winIndex[index]])
      ));
    }
    if(pointsIndex.isNotEmpty){
      list.add(PlayEntity(
          matchId: data?.matchId,
          playType: "总进球",
          items: List.generate(pointsIndex.length, (index) =>
            pointsIndex[index].toString())
      ));
    }
    await KingApi.sendPrediction(
      encodePlayType(list), data?.matchId);
    data = await KingApi.getKingDetail(data?.matchId ?? 0);
    hasCommit = true;
    update();
  }
}